import {config} from '../config'

const tips = {
    1: '抱歉,出现错误',
    1005: 'appKey无效',
    300: '不存在'
}


class HTTP {

    request(url, data = {}, method = "GET") {
        return new Promise(
            (resolve, reject) => {
                this._request(url,resolve,reject,data,method)
            }
        )
    }


    _request(url, resolve, reject, data = {}, method = "GET") {

        wx.request(
            {
                url: config.apiBaseUrl + url,
                method: method || "GET",
                data: data,
                header: {
                    'contentType': 'application/json',
                    'appKey': config.appkey
                },

                success: (res) => {

                    const code = res.statusCode.toString()
                    if (code.startsWith('2')) {
                        resolve(res.data)

                    } else {
                        reject()
                        this._showError(res.data.errorCode)

                    }
                },
                fail: (err) => {
                    reject()
                    this._showError()

                }
            }
        )
    }


    _showError(errCode = 1) {


        const tip=tips[errCode]
        wx.showToast({
            title:tip?tip:tips[errCode],
            icon: 'none',
            duration: 2000
        })

    }


}


export {HTTP}
